import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  Box,
  Container,
  Grid,
  Typography,
  Paper,
  Button,
  TextField,
  Card,
  CardContent,
  Chip,
  Divider,
  LinearProgress,
  Alert,
  AlertTitle,
  CircularProgress
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  Send as SendIcon,
  CheckCircle as CheckCircleIcon,
  Info as InfoIcon,
  Warning as WarningIcon,
  Error as ErrorIcon
} from '@mui/icons-material';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { atomDark } from 'react-syntax-highlighter/dist/esm/styles/prism';

import { RootState } from '../redux/store';
import { AppDispatch } from '../redux/store';
import { getChallengeById, submitSolution } from '../redux/slices/challengeSlice';
import { getPatternProgress } from '../redux/slices/progressSlice';
import { addAlert } from '../redux/slices/uiSlice';

// Define TestCase interface
interface TestCase {
  input: string;
  expectedOutput: string;
  description: string;
}

// Define ChallengeType interface with sampleCode property
interface ChallengeType {
  _id: string;
  title: string;
  description: string;
  pattern: {
    _id: string;
    name: string;
    category: string;
  };
  level: 'beginner' | 'intermediate' | 'advanced';
  scenario: string;
  requirements: string[] | string | Record<string, string>;
  hints?: string[] | string | Record<string, string>;
  testCases: TestCase[];
  timeLimit: number;
  difficulty: number;
  tags: string[];
  sampleCode?: string;
}

const Challenge: React.FC = () => {
  const { challengeId } = useParams<{ challengeId: string }>();
  const navigate = useNavigate();
  const dispatch = useDispatch<AppDispatch>();
  const [solution, setSolution] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const { t } = useTranslation();

  const { currentChallenge, loading: challengeLoading } = useSelector((state: RootState) => state.challenges);
  const { patternProgress, loading: progressLoading } = useSelector((state: RootState) => state.progress);

  useEffect(() => {
    if (challengeId) {
      dispatch(getChallengeById(challengeId));
    }
  }, [dispatch, challengeId]);

  useEffect(() => {
    if (currentChallenge?.pattern) {
      dispatch(getPatternProgress(currentChallenge.pattern._id));
    }
  }, [dispatch, currentChallenge]);

  const handleSolutionChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setSolution(e.target.value);
  };

  const handleSubmit = async () => {
    if (!solution.trim()) {
      dispatch(addAlert({
        type: 'error',
        message: t('challenge.errors.provideSolution')
      }));
      return;
    }

    setSubmitting(true);
    
    try {
      await dispatch(submitSolution({
        challengeId: challengeId!,
        solution
      }) as any).unwrap();
      
      dispatch(addAlert({
        type: 'success',
        message: t('challenge.success.submitted')
      }));
      
      if (currentChallenge?.pattern) {
        dispatch(getPatternProgress(currentChallenge.pattern._id) as any);
      }
    } catch (error: any) {
      console.error('Solution submission error:', error);
      let errorMessage = t('challenge.errors.submitFailed');
      
      if (error && typeof error === 'object') {
        if (error.message) {
          errorMessage = error.message;
        } else if (error.msg) {
          errorMessage = error.msg;
        }
      }
      
      dispatch(addAlert({
        type: 'error',
        message: errorMessage
      }));
    } finally {
      setSubmitting(false);
    }
  };

  const currentProgress = patternProgress?.find(p => p.challenge._id === challengeId);
  const isCompleted = currentProgress?.completed || false;
  const evaluation = currentProgress?.evaluation;

  if (challengeLoading || progressLoading || !currentChallenge) {
    return (
      <Box sx={{ width: '100%', mt: 4 }}>
        <LinearProgress />
      </Box>
    );
  }

  // Safely access hints and handle both string and array types
  const renderHints = () => {
    if (!currentChallenge.hints) return null;
    
    if (Array.isArray(currentChallenge.hints)) {
      return (
        <>
          <Typography variant="h6" gutterBottom>
            {t('challenge.hints')}
          </Typography>
          <Divider sx={{ mb: 2 }} />
          <ul>
            {currentChallenge.hints.map((hint, index) => (
              <li key={index}>
                <Typography>
                  {t(`challenge.hints.${currentChallenge.title}`, { defaultValue: hint })}
                </Typography>
              </li>
            ))}
          </ul>
        </>
      );
    } else if (typeof currentChallenge.hints === 'object') {
      // 处理对象类型
      return (
        <>
          <Typography variant="h6" gutterBottom>
            {t('challenge.hints')}
          </Typography>
          <Divider sx={{ mb: 2 }} />
          <ul>
            {Object.entries(currentChallenge.hints).map(([key, value], index) => (
              <li key={index}>
                <Typography>
                  {String(value)}
                </Typography>
              </li>
            ))}
          </ul>
        </>
      );
    } else {
      return (
        <>
          <Typography variant="h6" gutterBottom>
            {t('challenge.hints')}
          </Typography>
          <Divider sx={{ mb: 2 }} />
          <Typography paragraph>
            {t(`challenge.hints.${currentChallenge.title}`, { defaultValue: currentChallenge.hints })}
          </Typography>
        </>
      );
    }
  };
  
  // Safely access sampleCode
  const renderSampleCode = () => {
    // Access sampleCode using optional chaining and type assertion
    const sampleCode = (currentChallenge as any).sampleCode;
    
    if (!sampleCode) return null;
    
    return (
      <>
        <Typography variant="h6" gutterBottom>
          {t('challenge.sampleCode')}
        </Typography>
        <Divider sx={{ mb: 2 }} />
        <SyntaxHighlighter language="typescript" style={atomDark}>
          {sampleCode}
        </SyntaxHighlighter>
      </>
    );
  };

  const renderEvaluationAlert = () => {
    if (!evaluation) return null;

    const { rating, feedback } = evaluation;
    
    let severity: 'success' | 'info' | 'warning' | 'error';
    let icon;
    
    switch (rating) {
      case 'Excellent':
        severity = 'success';
        icon = <CheckCircleIcon />;
        break;
      case 'Good':
        severity = 'info';
        icon = <InfoIcon />;
        break;
      case 'Satisfactory':
        severity = 'warning';
        icon = <WarningIcon />;
        break;
      case 'Unsatisfactory':
        severity = 'error';
        icon = <ErrorIcon />;
        break;
      default:
        severity = 'info';
        icon = <InfoIcon />;
    }

    // 检查评估是否使用了AI辅助
    const isWithoutAI = feedback.includes('without AI assistance') || 
                       feedback.includes('未使用AI') || 
                       feedback.includes('未配置') ||
                       (feedback.includes('default') && feedback.includes('evaluation'));
                       
    // 检查是否明确使用了DeepSeek
    const isDeepSeekEvaluation = feedback.includes('[DeepSeek评估]') ||
                                (feedback.includes('DeepSeek') && !feedback.includes('未配置')) ||
                                (feedback.includes('deepseek') && !feedback.includes('not configured'));
    
    return (
      <>
        <Alert 
          severity={severity}
          icon={icon}
          sx={{ mt: 3, mb: isWithoutAI ? 1 : 3 }}
        >
          <AlertTitle>{t(`challenge.ratings.${rating}`)}</AlertTitle>
          {/* 从DeepSeek评估标记中提取实际反馈 */}
          {isDeepSeekEvaluation && feedback.includes('[DeepSeek评估]') 
            ? feedback.replace('[DeepSeek评估]', '') 
            : feedback}
        </Alert>
        
        {isWithoutAI && (
          <Alert 
            severity="info"
            sx={{ mb: 3 }}
          >
            <AlertTitle>{t('common.tip')}</AlertTitle>
            {t('challenge.evaluation.withoutAI')}
          </Alert>
        )}
        
        {isDeepSeekEvaluation && (
          <Alert
            severity="success"
            sx={{ mb: 3 }}
          >
            <AlertTitle>{t('common.tip')}</AlertTitle>
            {t('challenge.evaluation.evaluatingWithDeepSeek')}
          </Alert>
        )}
      </>
    );
  };

  const renderRequirements = () => {
    if (!currentChallenge.requirements) return null;
    
    // 简化处理，统一呈现要求列表
    if (Array.isArray(currentChallenge.requirements)) {
      return (
        <ul>
          {currentChallenge.requirements.map((req, index) => (
            <li key={index}>
              <Typography>
                {t(`challenge.requirements.${currentChallenge._id}.${index}`, { defaultValue: req })}
              </Typography>
            </li>
          ))}
        </ul>
      );
    } else if (typeof currentChallenge.requirements === 'object') {
      // 处理对象类型 - 不应该直接翻译键名，而是翻译值
      return (
        <ul>
          {Object.entries(currentChallenge.requirements).map(([key, value], index) => (
            <li key={index}>
              <Typography>
                {t(`challenge.requirements.${currentChallenge._id}.${key}`, { defaultValue: String(value) })}
              </Typography>
            </li>
          ))}
        </ul>
      );
    } else {
      return (
        <Typography paragraph>
          {t(`challenge.requirements.${currentChallenge._id}`, { defaultValue: String(currentChallenge.requirements) })}
        </Typography>
      );
    }
  };

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Button
        startIcon={<ArrowBackIcon />}
        onClick={() => navigate(`/patterns/${currentChallenge.pattern._id}`)}
        sx={{ mb: 2 }}
      >
        {t('challenge.backToPattern')}
      </Button>
      
      <Paper sx={{ mb: 4, p: 3 }}>
        <Grid container spacing={2}>
          <Grid item xs={12} md={8}>
            <Typography variant="h4" component="h1" gutterBottom>
              {t(`challenge.titles.${currentChallenge.title}`, { defaultValue: currentChallenge.title })}
            </Typography>
            <Chip
              label={t(`challenge.levels.${currentChallenge.level}`)}
              color={
                currentChallenge.level === 'beginner'
                  ? 'primary'
                  : currentChallenge.level === 'intermediate'
                  ? 'secondary'
                  : 'error'
              }
              sx={{ mr: 1 }}
            />
            <Chip
              label={t(`patterns.names.${currentChallenge.pattern.name}`, { defaultValue: currentChallenge.pattern.name })}
              color="info"
              sx={{ mr: 1 }}
            />
            {isCompleted && (
              <Chip
                icon={<CheckCircleIcon />}
                label={t('challenge.completed')}
                color="success"
                variant="outlined"
                sx={{ ml: 1 }}
              />
            )}
          </Grid>
        </Grid>
      </Paper>

      <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 3, height: '100%' }}>
            <Typography variant="h6" gutterBottom>
              {t('challenge.challengeDescription')}
            </Typography>
            <Divider sx={{ mb: 2 }} />
            <Typography paragraph>
              {t(`challenge.descriptions.${currentChallenge.description}`, { defaultValue: currentChallenge.description })}
            </Typography>
            
            {currentChallenge.scenario && (
              <>
                <Typography variant="h6" gutterBottom>
                  {t('challenge.scenario')}
                </Typography>
                <Divider sx={{ mb: 2 }} />
                <Typography paragraph>
                  {t(`challenge.scenarios.${currentChallenge.scenario}`, { defaultValue: currentChallenge.scenario })}
                </Typography>
              </>
            )}
            
            <Typography variant="h6" gutterBottom>
              {t('challenge.requirements')}
            </Typography>
            <Divider sx={{ mb: 2 }} />
            {renderRequirements()}
            
            {renderHints()}
            {renderSampleCode()}
          </Paper>
        </Grid>
        
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('challenge.yourSolution')}
              </Typography>
              <Divider sx={{ mb: 2 }} />
              
              {renderEvaluationAlert()}
              
              <TextField
                label={t('challenge.yourSolution')}
                multiline
                rows={15}
                fullWidth
                variant="outlined"
                value={solution}
                onChange={handleSolutionChange}
                sx={{ mb: 2, fontFamily: 'monospace' }}
                placeholder="// Write your solution here..."
                defaultValue={currentProgress?.lastSubmission?.code || ''}
              />
              
              <Box display="flex" justifyContent="flex-end">
                <Button
                  variant="contained"
                  color="primary"
                  endIcon={submitting ? <CircularProgress size={20} color="inherit" /> : <SendIcon />}
                  onClick={handleSubmit}
                  disabled={submitting}
                >
                  {submitting ? t('challenge.submitting') : t('challenge.submitSolution')}
                </Button>
              </Box>
              
              {currentProgress?.attempts !== undefined && currentProgress.attempts > 0 && (
                <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
                  {t('challenge.attempts', { count: currentProgress.attempts })}
                </Typography>
              )}
              
              {evaluation?.suggestions && (
                <Box mt={3}>
                  <Typography variant="h6" gutterBottom>
                    {t('challenge.improvement.title')}
                  </Typography>
                  <Divider sx={{ mb: 2 }} />
                  <Typography paragraph>
                    {evaluation.suggestions}
                  </Typography>
                </Box>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Container>
  );
};

export default Challenge; 